// pages/scanCode/firmware/property/index.js
const { MemberModel } = require('../../../../utils/member-model.js');
var memberModel = new MemberModel();
const { CurrencyShopModel } = require('../../../../utils/currencyshop-model.js')
const currencyShopModel = new CurrencyShopModel()
const { MarketingModel } = require('../../../../utils/marketing-model.js');
const marketingModel = new MarketingModel();
var utils =
  require("../../../../utils/util.js");
const {
  globalData
} = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    islayerShow: false,
    layerData: {},
    orderPaySummaryList: [],
    paymentText: {},
    timer: null,
    count: 30,
    hotMealShow: true, // 热销套餐是否显示
    machineInstanceSlotId: '',
    isLogin: false,
    navigationHeight: 64,
    navigationTop: 32,
    navigationLeft: 10,
    capsuleWidth: 87,
    shopName: '', // 门店
    shopId: '',
    leverCode: '', // 等级
    leverName: '', // 等级名称
    memberName: '', // 会员名称
    svipType: '', //SVIP类型 1:是 0:否
    gameCurrency: '',
    gameTicket: '',
    machineName: '',
    modeList: [],
    currencies: [],
    src: 'https://oss.kiscloud.net/wechat/images/no_phone.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const navigationBtnObj = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: res => {
        this.setData({
          machineInstanceSlotId: options.machineInstanceSlotId,
          navigationHeight: res.statusBarHeight + navigationBtnObj.height + (navigationBtnObj.top - res.statusBarHeight) * 2,
          navigationTop: navigationBtnObj.top,
          navigationLeft: res.windowWidth - navigationBtnObj.right,
          capsuleWidth: navigationBtnObj.width
        })
      }
    })
  },
  setExchange: function () {
    this.setData({
      islayerShow: !this.data.islayerShow
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    clearInterval(this.data.timer)
    this.setData({
      isLogin: globalData.isLogin,
      count: 30,
      timer: null
    }, () => {
      this.getUserInfo(); //会员信息
      this.getCoinList(); //几币几局
    })
  },
  timeFuc () {
    this.setData({
      timer: setInterval(() => {
        let count = this.data.count -1
        this.setData({
          count
        })
        if (this.data.count === 0) {
          this.cleanTimer()
          this.goUrl('2')
        }
      }, 1000)
    })
  },
  cleanTimer () {
    clearInterval(this.data.timer)
    this.setData({
      timer: null,
      count: 30
    })
},
  goUrl (type) {
    wx.navigateTo({
      url: `/pages/scanCode/firmware/isUsed/index?type=${type}`
    })
  },
  goBack () {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  /**
   *微信会员信息
   */
  getUserInfo: function () {
    if (globalData.isLogin) {
      memberModel.userInfo({
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        wx.setStorageSync('memberId', data.memberId);
        var that = this;
        that.setData({
          memberName: data.nickname || "", //会员名称
          src: data.avatarUrl || "https://oss.kiscloud.net/wechat/images/no_phone.png", //会员头像
          leverCode: data.memberLevel ? 'V' + data.memberLevel : "V0", //会员等级
          leverName: data.memberLevelName ? data.memberLevelName : "", //等级名称
          svipType: data.svipType //SVIP类型 1: 是 0: 否
        });
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  /**
   * 获取几币几局
   */
getCoinList () {
  marketingModel.firmwareGearList({
    merchantId: wx.getStorageSync('merchantId'),
    machineInstanceSlotId: this.data.machineInstanceSlotId
  }).then(data => {
    let arr = data.skqConfigDTOList || []
    this.setData({
      paymentText: data.text[0],
      shopName: data.shopName || '',
      shopId: arr.length > 0 ? arr[0].shopId : '',
      machineName: arr.length > 0 ? arr[0].deviceName : '',
      gameCurrency: data.coinTotal || 0,
      gameTicket: data.gameCouponTotal || 0,
      modeList: arr,
      hotMealShow: arr.every((val,i) => {
        return val.show === false
      })
    }, () => {
      if (this.data.hotMealShow) {
        this.getCurrency()
      } else {
        this.timeFuc()
      }
    })
  }).catch(err => {
    wx.showToast({
      title: `${err.error}`,
      icon: 'none',
      duration: 2000
    })
  })
},
goPay (e) {
  this.setExchange()
  let meal = e.currentTarget.dataset.meal
  meal.money = meal.money.toFixed(2)
  this.setData({
    layerData: meal
  })
},
paySubmit () {
  let that = this
  let merchantId = wx.getStorageSync('merchantId')
  marketingModel.remoteCoinCreate({
    merchantId, //商户id
    shopId: this.data.layerData.shopId, //门店id
    deviceId: this.data.layerData.deviceId,
    gears: this.data.layerData.gears
  }).then(data => {
    this.setData({
      orderPaySummaryList: data.orderPaySummaryList
    })
    currencyShopModel.createPayOrder({
      merchantId,
      shopId: this.data.layerData.shopId,
      orderCode: data.orderCode,
      channel: 'WEIXIN',
      payMethod: 'WAP_PAY'
    }).then(({
      payInfo
    }) => {
      wx.requestPayment({
        timeStamp: payInfo.timeStamp,
        nonceStr: payInfo.nonceStr,
        package: payInfo.package,
        signType: payInfo.signType,
        paySign: payInfo.paySign,
        success: () => {
          this.setData({
            islayerShow:false
          })
          wx.navigateTo({
            url: '/pages/scanCode/firmware/result/index?orderCode=' + data.orderCode + '&shopId=' + this.data.layerData.shopId
          })
        },
        fail: () => {}
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  }).catch(err => {
    wx.showToast({
      title: `${err.error}`,
      icon: 'none',
      duration: 2000
    })
  })
},
goPlay (e) {
  let meal = e.currentTarget.dataset.meal
  if (!meal.show) return
  this.cleanTimer()
  wx.showLoading({
    title: '启动中',
    mask: true
  })
  marketingModel.firmwareGoGame({
    merchantId: wx.getStorageSync('merchantId'), //商户id
    shopId: meal.shopId, //门店id
    deviceId: meal.deviceId,
    realCoin: meal.realCoin,
    coin: meal.coin,
    gears: meal.gears
  }).then(data => {
    this.cleanTimer()
    wx.hideLoading()
    if (data.code === 1) {
      this.goUrl('1')
    } else {
      wx.navigateTo({
        url: '/pages/scanCode/firmware/result/index?type=0',
      })
    }
  }).catch(err => {
    wx.showToast({
      title: `${err.error}`,
      icon: 'none',
      duration: 2000
    })
  })
  this.cleanTimer()
  this.timeFuc()
},
getCurrency() {
  currencyShopModel.getCurrencyv2({
    merchantId: wx.getStorageSync('merchantId'),
    shopId: this.data.shopId,
  }).then(data => {
    const currencies = (data || []).sort((a,b) => {
      return a.goodsPrices[0].amount - b.goodsPrices[0].amount
    }).slice(0,1).map(item => {
      item.satisfyActivityTypeList = item.satisfyActivityTypeList || []
      let rightsType = 0
      if (item.goodsTags && item.goodsTags != null && item.goodsTags.length > 0) {
        item.goodsTags.forEach(element => {
          if (element.goodsTagId === 'dwj_svip') {
            rightsType = 1
          }
        })
      }
      if (rightsType === 1 || !item.satisfyActivityTypeList.length) {
        item.satisfyActivityTypeList = []
      } else if (item.satisfyActivityTypeList.length === 1) {
        item.satisfyActivityTypeList = item.satisfyActivityTypeList
      } else if (item.satisfyActivityTypeList.length === 2 && item.satisfyActivityTypeList.includes(7) && item.satisfyActivityTypeList.includes(8)) {
        item.satisfyActivityTypeList = [8]
      } else {
        item.satisfyActivityTypeList = [5]
      }
      let commodityPrices = 0;
      const goodsPrices = item.goodsPrices.map(price => {
        const split = price.amount.toFixed(2).split('.')
        if (price.priceType === 0) {
          commodityPrices = price.amount
        }
        return {
          ...price,
          int: split[0],
          float: split[1]
        }
      })
      return {
        ...item,
        goodsPrices,
        rightsType,
        commodityPrices
      }
    })
    this.setData({
      currencies: currencies
    })
  }).catch(err => {
    wx.showToast({
      title: `${err.error}`,
      icon: 'none'
    })
  })
},
goCommitOrder (e) {
  let currency = e.currentTarget.dataset.currency
    wx.navigateTo({
      url: `/pages/currencyShop/currencyDetail/index?shopName=${this.data.shopName}&currency=${encodeURIComponent(JSON.stringify(currency))}&shopId=${this.data.shopId}&type=${0}&entrance=${0}`
    })
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.cleanTimer()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})